package com.cmcc.driver.ui.profile

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.View
import android.widget.RadioButton
import android.widget.RadioGroup
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.alibaba.android.arouter.facade.annotation.Route
import com.cmcc.driver.R
import com.cmcc.driver.config.AppConfig.FILE_URL
import com.cmcc.driver.config.DriverPath
import com.cmcc.driver.data.entity.request.CarUpdateRequest
import com.cmcc.driver.data.entity.response.CarCategory
import com.cmcc.driver.data.entity.response.CarInfo
import com.cmcc.driver.databinding.ActivityCarManagerBinding
import com.cmcc.driver.ui.base.BasicActivity
import com.cmcc.driver.ui.dialog.AppAlertDialog
import com.cmcc.driver.ui.dialog.AppProgressDialog
import com.cmcc.driver.ui.profile.viewModel.TaxiInfoViewModel
import com.cmcc.shared.utils.SpHelper
import com.cmcc.shared.utils.showToast

/**
 * Taxi Information Edit.
 */
@Route(path = DriverPath.TAXI_INFORMATION)
class TaxiInfoActivity : BasicActivity() {

    private lateinit var binding: ActivityCarManagerBinding

    private var viewModel: TaxiInfoViewModel? = null

    private var carInfo: CarInfo? = null
    private var categoryInfo: MutableList<CarCategory>? = ArrayList()
    private var progressDialog: AppProgressDialog? = null

    override fun initialize(savedInstanceState: Bundle?) {
        viewModel = ViewModelProviders.of(this).get(TaxiInfoViewModel::class.java)
        progressDialog = AppProgressDialog(this)

        viewModel?.requestCarCategory()

        viewModel?.requestCarInfo()

        viewModel?.plus()
    }

    override fun initView(savedInstanceState: Bundle?) {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_car_manager)
        binding.appbar.toolbar.setNavigationOnClickListener { finish() }
        binding.appbar.title.text = getString(R.string.taxi_info_title)
        binding.viewModel = viewModel
        binding.carNumber.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
                Log.i(TAG, s.toString())
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
                Log.i(TAG, s.toString())
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                if (count == 0) {
                    binding.confirm.isClickable = false
                    binding.confirm.setBackgroundResource(R.drawable.shape_button_gray_with_corner_x25)
                } else {
                    binding.confirm.isClickable = true
                    binding.confirm.setBackgroundResource(R.drawable.shape_button_accent_with_corner_x25)
                }
            }

        })
    }

    override fun initEvent(savedInstanceState: Bundle?) {
        viewModel?._confirmSelector?.observe(this, Observer {

            var categoryCode = ""
            val idCard: String = binding.carNumber.text.toString()
            categoryInfo?.forEach { carCategory ->
                if (binding.carTypeGroup.checkedRadioButtonId == carCategory.customerId) {
                    categoryCode = carCategory.code.toString()
                    return@forEach
                }
            }

            if (idCard.isNullOrBlank()) {
                showToast(this, "请输入车牌号！")
                return@Observer
            }

            val carRequest = CarUpdateRequest(
                carInfo?.id ?: "0",
                idCard,
                carInfo?.model ?: "",
                categoryCode
            )

            progressDialog?.show()
            viewModel?.updateCarInfo(carRequest)
        })

        binding.carTypeGroup.setOnCheckedChangeListener { group, checkedId ->
            categoryInfo?.forEach { carCategory ->
                if (checkedId == carCategory.customerId) {
                    binding.carUrl =
                        FILE_URL.plus("icon/").plus("ic_".plus(carCategory.code).plus(".png"))
                    return@forEach
                }
            }


        }

    }

    override fun initObserver(savedInstanceState: Bundle?) {
        //我的车的信息
        viewModel?.carInfo?.observe(this, Observer { response ->
            carInfo = response
            binding.carNumber.setText(carInfo?.idCard)
            //拿到车的信息之后 再去 获取车类型信息

        })
        //我的车辆类别
        viewModel?.carCategory?.observe(this, Observer { response ->
            categoryInfo?.clear()

            response?.forEach { carCategory ->
                var category = carCategory
                category.customerId = -1
                categoryInfo?.add(category)
            }

        })

        viewModel?.radioMsg?.observe(this, Observer {
            if (it) {
                addRadioButton(binding.carTypeGroup)
            }
        })

        viewModel?.resMsg?.observe(this, Observer { resMsg ->
            progressDialog?.dismiss()
            if (resMsg.code == 200) {
                AppAlertDialog(this).setContent(getString(R.string.update_taxi_info_message))
                    .setNavigation("", null, false)
                    .setPositive(getString(R.string.make_sure), View.OnClickListener {
                        finish()
                    }).show()
            } else {
                showToast(this, resMsg.msg)
            }
        })
    }

    private fun addRadioButton(radioGroup: RadioGroup) {


        for (index in 0..categoryInfo!!.size - 1) {
            categoryInfo!!.get(index).customerId = index

            val radioButton = RadioButton(this)
            setRadioAttribute(
                radioButton,
                categoryInfo!!.get(index).name,
                categoryInfo!!.get(index).customerId,
                categoryInfo!!.get(index).id,
                categoryInfo!!.get(index).code
            )

            radioGroup.addView(radioButton)
        }

    }

    private fun setRadioAttribute(
        radioButton: RadioButton,
        name: String,
        customerId: Int,
        id: String,
        code: String?
    ) {
        radioButton.setPaddingRelative(0, 0, 18, 0)

        if (Build.VERSION.SDK_INT >= 23) {
            var type = SpHelper.getParam(this, "Mode", "type", "1")

            //当前是夜间模式 设置成白天模式
            if (type == "1") {
                val colorStateList =
                    this.resources.getColorStateList(R.color.driver_signin_btn_main_color, null)
                radioButton.buttonTintList = colorStateList
            } else {
                val colorStateList =
                    this.resources.getColorStateList(R.color.driver_signin_btn_main, null)
                radioButton.buttonTintList = colorStateList
            }
        }

        var type = SpHelper.getParam(this, "Mode", "type", "1");
        //当前是夜间模式
        if (type.equals("1")) {
            radioButton.setTextColor(Color.parseColor("#FFFFFF"))
        }
        //当前是白天模式
        else {
            radioButton.setTextColor(Color.parseColor("#000000"))
        }
        radioButton.textSize = 18f
        radioButton.id = customerId
        radioButton.text = name
        //是否选择
        if (carInfo?.vehicleTypeCode.equals(code)) {
            radioButton.isChecked = true
            binding.carUrl = FILE_URL.plus("icon/").plus("ic_".plus(code).plus(".png"))
        } else {
            radioButton.isChecked = false
        }


    }


}